/**
 * Location.m by Giraldo Rosales.
 * Visit www.liquidgear.net for documentation and updates.
 *
 * Copyright (c) 2009 Nitrogen Design, Inc. All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 **/
#if LG_USE_LOCATION

#import "Location.h"
#import "WebController.h"
#import "Utils.h"

@implementation Location

@synthesize viewController, locationManager;

- (id) initWithController:(WebController *)controller accuracy:(int)accuracy {
	self = [super init];
	
	if (self != nil) {
		self.viewController		= controller;
		self.locationManager	= [[[CLLocationManager alloc] init] autorelease];
		if(accuracy < 3) {
			self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
		}
		else if(accuracy >= 3 && accuracy < 10) {
			self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
		}
		else if(accuracy >= 10 && accuracy < 100) {
			self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
		}
		else if(accuracy >= 100) {
			self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
		}
		else {
			self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
		}
		
		self.locationManager.delegate = self;
	}
	
	return self;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	NSDictionary *coords	= [NSDictionary dictionaryWithObjectsAndKeys:
														 [[[NSString alloc] autorelease] initWithFormat:@"%f", newLocation.coordinate.latitude], @"latitude",
														 [[[NSString alloc] autorelease] initWithFormat:@"%f", newLocation.coordinate.longitude], @"longitude",
														 [[[NSString alloc] autorelease] initWithFormat:@"%f", newLocation.altitude], @"altitude",
														 [[[NSString alloc] autorelease] initWithFormat:@"%f", newLocation.speed], @"speed",
														 [[[NSString alloc] autorelease] initWithFormat:@"%f", newLocation.course], @"heading",
														 nil
														 ];
	
	NSDictionary *callback	= [NSDictionary dictionaryWithObjectsAndKeys:coords, @"coords",nil];
	[[[Utils alloc] autorelease] jsCall:viewController.webView type:@"location" data:callback directCall:nil];
}

// Called when there is an error getting the location
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
	NSMutableString *errorString = [[[NSMutableString alloc] init] autorelease];
	
	if ([error domain] == kCLErrorDomain) {
		switch ([error code]) {
				// This error code is usually returned whenever user taps "Don't Allow" in response to
				// being told your app wants to access the current location. Once this happens, you cannot
				// attempt to get the location again until the app has quit and relaunched.
				//
				// "Don't Allow" on two successive app launches is the same as saying "never allow". The user
				// can reset this for all apps by going to Settings > General > Reset > Reset Location Warnings.
				//
			case kCLErrorDenied:
				[errorString appendFormat:@"%@\n", NSLocalizedString(@"LocationDenied", nil)];
				break;
				
				// This error code is usually returned whenever the device has no data or WiFi connectivity,
				// or when the location cannot be determined for some other reason.
				//
				// CoreLocation will keep trying, so you can keep waiting, or prompt the user.
				//
			case kCLErrorLocationUnknown:
				[errorString appendFormat:@"%@\n", NSLocalizedString(@"LocationUnknown", nil)];
				break;
				
				// We shouldn't ever get an unknown error code, but just in case...
				//
			default:
				[errorString appendFormat:@"%@ %d\n", NSLocalizedString(@"GenericLocationError", nil), [error code]];
				break;
		}
	} else {
		// We handle all non-CoreLocation errors here
		// (we depend on localizedDescription for localization)
		[errorString appendFormat:@"Error domain: \"%@\"  Error code: %d\n", [error domain], [error code]];
		[errorString appendFormat:@"Description: \"%@\"\n", [error localizedDescription]];
	}
	
	NSDictionary *callback	= [NSDictionary dictionaryWithObjectsAndKeys:
														 errorString, @"error",
														 nil
														 ];
	
	[[[Utils alloc] autorelease] jsCall:viewController.webView type:@"location" data:callback directCall:nil];
}

- (void)dealloc {
	[self.locationManager release];
	[super dealloc];
}

@end
#endif